package dbtool

import (
	"fmt"
	"github.com/jinzhu/gorm"
)

func GeneralListGORM(database *gorm.DB, params *ListByPageParams) (db *gorm.DB) {
	db = database
	if params == nil {
		return
	}
	if len(params.Fields) > 0 {
		db = db.Select(params.Fields)
	} else if len(params.IgnoreFields) > 0 {
		db = db.Omit(params.IgnoreFields...)
	}
	if len(params.SortBy) > 0 {
		if params.SortDirection {
			db = db.Order(fmt.Sprintf("%s ASC", params.SortBy))
		} else {
			db = db.Order(fmt.Sprintf("%s DESC", params.SortBy))
		}
	}
	if params.PageNumber > 0 && params.PageSize > 0 {
		offset := (params.PageNumber - 1) * params.PageSize
		db = db.Offset(offset).Limit(params.PageSize)
	}
	return
}
